package com.tql.test_02;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class JUCPcTest {
    public static void main(String[] args) {
        PCTest2 pcTest2 = new PCTest2();
        new Thread(()->{ for (int i = 0; i < 10; i++) pcTest2.increment(); },"A").start();
        new Thread(()->{ for (int i = 0; i < 10; i++) pcTest2.decrment(); },"B").start();
        new Thread(()->{ for (int i = 0; i < 10; i++) pcTest2.increment(); },"C").start();
        new Thread(()->{ for (int i = 0; i < 10; i++) pcTest2.decrment(); },"D").start();

    }
}
//资源类，降低耦合，线程处理资源类
//生产者消费者问题 六字核心  判断等待 业务  通知唤醒
class PCTest2{
    Lock lock= new ReentrantLock();
    //Condition取代了对象监视器的使用，优点：可以实现精确唤醒线程
    Condition condition = lock.newCondition();
    int num=0;
    //生产 +1
    public  void increment()  {
        lock.lock();
        try {
            //使用while
            //如果使用if 会造成锁失效
            while(num!=0){
                try {
                   condition.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            num++;
            System.out.println(Thread.currentThread().getName()+"执行了加操作 "+num);
            condition.signalAll();

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //记得要释放锁，不释放造成死锁现象
            lock.unlock();
        }

    }
    //消费 -1
    public  synchronized void decrment()  {
        lock.lock();
        try {
            while(num==0){
                try {
                    condition.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            num--;
            System.out.println(Thread.currentThread().getName()+"执行了减操作 "+num);
            condition.signalAll();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

}